<template>
  <div class="shop-status-container">
    <h1>店铺操作 (API 测试)</h1>

    <div v-if="loading" class="loading-text">
      获取状态中...
    </div>

    <div v-if="error" class="error-text">
      发生错误: {{ error }}
    </div>

    <div v-if="!loading && currentStatus !== null" class="status-display">
      <h2>当前营业状态:
        <el-tag :type="currentStatus === 1 ? 'success' : 'info'">
          {{ currentStatus === 1 ? '营业中' : '打烊中' }}
        </el-tag>
      </h2>

      <div class="controls">
        <p>切换状态:</p>
        <el-switch
          v-model="isOperating"
          size="large"
          inline-prompt
          active-text="营业"
          inactive-text="打烊"
          @change="handleStatusChange"
          :loading="switchLoading"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
// 导入我们刚刚创建的 API 函数
import { getShopStatus, setShopStatus } from '@/api/shop';

// --- State ---
const loading = ref(true); // 初始页面加载状态
const switchLoading = ref(false); // 切换开关时的加载状态
const error = ref<string | null>(null);
const currentStatus = ref<0 | 1 | null>(null);

// --- Computed Property ---
// 创建一个计算属性来双向绑定 el-switch
const isOperating = computed({
  get: () => currentStatus.value === 1,
  set: (newValue: boolean) => {
    currentStatus.value = newValue ? 1 : 0;
  }
});

// --- Methods ---
const fetchStatus = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await getShopStatus();
    currentStatus.value = response.data;
  } catch (e: any) {
    error.value = e.message || '获取状态失败';
  } finally {
    loading.value = false;
  }
};

const handleStatusChange = async (newValue: boolean) => {
  const newStatus = newValue ? 1 : 0;
  switchLoading.value = true;
  try {
    await setShopStatus(newStatus);
    currentStatus.value = newStatus; // 只有在 API 调用成功后才真正更新状态
    ElMessage.success('状态设置成功！');
  } catch (e: any) {
    ElMessage.error(e.message || '状态设置失败');
    // 如果设置失败，将开关恢复到之前的状态
    currentStatus.value = newStatus === 1 ? 0 : 1;
  } finally {
    switchLoading.value = false;
  }
};

// --- Lifecycle Hook ---
onMounted(() => {
  fetchStatus();
});
</script>

<style scoped>
.shop-status-container {
  padding: 30px;
  font-family: sans-serif;
  background-color: #fff;
  margin: 20px;
  border-radius: 8px;
}
.status-display {
  margin-top: 20px;
}
.controls {
  margin-top: 30px;
  display: flex;
  align-items: center;
  gap: 15px;
}
.loading-text, .error-text {
  padding: 20px;
  border-radius: 4px;
}
.error-text {
  background-color: #fee;
  color: red;
}
</style>
